import { createRouter, createWebHistory } from 'vue-router'
import { useLoginStore } from '@/stores/login';
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: true }
    },
    {
      path: '/login',
      name: 'login',
      component: import('../views/LoginView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/register',
      name: 'register',
      component: import('../views/RegisterView.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/admin/aboutUs',
      name: 'aboutus',
      component: () => import('../views/AboutView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/admin/codeGenerate',
      name: 'codeGenerate',
      component: () => import('../views/CodeGenerateView.vue'),
      meta: { requiresAuth: true }
    },
  ]
})
//添加路由的前置守卫，做登陆状态的检测
router.beforeEach(async (to, from) => {
  if (to.meta.requiresAuth) {//判断当前界面是否需要鉴权
    //登陆状态的存储器
    const loginStore = useLoginStore();
    if (!loginStore.isLogin()) {
      // 将用户重定向到登录页面
      return { path: '/login' }
    }
  }
})
export default router
